package cn.akira.domain.strategy.service.rule.tree.impl;

import cn.akira.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import cn.akira.domain.strategy.repository.IStrategyRepository;
import cn.akira.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.akira.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author fjl95
 * @date 2025/5/16
 * @description 未解锁节点
 */
@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    //用户抽奖次数
    private Long userRaffleCount = 10L;
    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-次数锁 userID:{},strategyId:{},awardID:{}", userId, strategyId,awardId);
        long raffleCount = 0L;
        try{
            raffleCount = Long.parseLong(ruleValue);
        }catch (Exception e){
            throw new RuntimeException("规则过滤-次数锁异常 ruleValue:"+ruleValue+"配置不正确");
        }

        // 查询用户抽奖次数 - 当天的；策略ID:活动ID 1:1 的配置，可以直接用 strategyId 查询。
        Integer userRaffleCount = strategyRepository.queryTodayUserRaffleCount(userId, strategyId);

        //如果当前用户抽奖次数大于设定阈值
        if(userRaffleCount >= raffleCount){
            //设置状态ALLOW，由流程寻找对应下一节点
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .build();
        }
        //设置状态TAKE_OVER,由流程寻找下一节点
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .build();
    }
}
